<template>
  <div class="app-container">
    <div class="top-section-container">
      <div class="content-header">
        <h1>预约管理/<small>套餐管理</small></h1>
        <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>预约管理</el-breadcrumb-item>
          <el-breadcrumb-item>套餐管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="bottom-section-container">
      <div class="filter-container box">
        <el-input
            v-model="searchText"
            placeholder="编码/名称/助记码"
            style="width: 15rem; margin-right: 0.625rem;margin-top:10px"
            class="filter-item"
            @keyup.enter="findPage"
        ></el-input>
        <el-button type="primary" @click="findPage">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>

      <el-table
          :data="dataList"
          border
          stripe
          style="width: 100%; margin-top: 1.25rem;"
          class="datatable"
      >
        <el-table-column type="index" label="序号" align="center" width="60px"></el-table-column>
        <el-table-column label="图片" align="center" width="120px">
          <template #default="scope">
            <img
                :src="'http://q22u8a96w.bkt.clouddn.com/' + scope.row.img"
                alt="套餐图片"
                style="max-width: 100%; max-height: 80px; object-fit: contain;"
                v-if="scope.row.img"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="套餐名称" align="center" min-width="120px"></el-table-column>
        <el-table-column prop="code" label="套餐编码" align="center" width="100px"></el-table-column>
        <el-table-column prop="helpCode" label="助记码" align="center" width="100px"></el-table-column>
        <el-table-column prop="sex" label="适用性别" align="center" width="80px">
          <template #default="scope">
            <span>{{ scope.row.sex == '0' ? '不限' : scope.row.sex == '1' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="适用年龄" align="center" width="80px"></el-table-column>
        <el-table-column prop="price" label="价格" align="center" width="80px"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" min-width="150px"></el-table-column>
        <el-table-column prop="attention" label="注意事项" align="center" min-width="150px"></el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
        ></el-pagination>
      </div>
    </div>

    <el-dialog title="新增套餐" v-model="dialogFormVisible4Add" :close-on-click-modal="false" width="55rem">
      <el-form :model="formData" :rules="rules" ref="dataAddForm" label-width="6.25rem">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="套餐编码" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="助记码" prop="helpCode">
          <el-input v-model="formData.helpCode"></el-input>
        </el-form-item>
        <el-form-item label="适用性别" prop="sex"> <el-radio-group v-model="formData.sex">
          <el-radio label="0">不限</el-radio>
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="适用年龄" prop="age">
          <el-input v-model="formData.age"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="formData.attention" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="套餐图片" prop="img">
          <el-upload
              class="avatar-uploader"
              action="/setmeal/upload"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择检查组" prop="checkGroupIds">
          <el-transfer
              v-model="checkGroupIds"
              :data="checkGroupList"
              :titles="['可选检查组', '已选检查组']"
              :props="{ key: 'id', label: 'name' }"
              filterable
          ></el-transfer>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible4Add = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="编辑套餐" v-model="dialogFormVisible4Edit" :close-on-click-modal="false" width="55rem">
      <el-form :model="formData" :rules="rules" ref="dataEditForm" label-width="6.25rem">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="套餐编码" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="助记码" prop="helpCode">
          <el-input v-model="formData.helpCode"></el-input>
        </el-form-item>
        <el-form-item label="适用性别" prop="sex"> <el-radio-group v-model="formData.sex">
          <el-radio label="0">不限</el-radio>
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="适用年龄" prop="age">
          <el-input v-model="formData.age"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="formData.attention" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="套餐图片" prop="img">
          <el-upload
              class="avatar-uploader"
              action="/setmeal/upload"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择检查组" prop="checkGroupIds">
          <el-transfer
              v-model="checkGroupIds"
              :data="checkGroupList"
              :titles="['可选检查组', '已选检查组']"
              :props="{ key: 'id', label: 'name' }"
              filterable
          ></el-transfer>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'; // 引入Plus图标

// 数据模型
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  queryString: null,
});
const dataList = ref([]); // 当前页的套餐列表
const formData = reactive({}); // 表单数据（新增/编辑）
const dialogFormVisible4Add = ref(false); // 新增弹窗显示控制
const dialogFormVisible4Edit = ref(false); // 编辑弹窗显示控制
const searchText = ref(''); // 搜索框内容
const checkGroupList = ref([]); // 所有检查组列表 (用于穿梭框)
const checkGroupIds = ref([]); // 当前套餐包含的检查组 ID 列表 (用于穿梭框绑定)
const imageUrl = ref(''); // 图片预览URL

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '套餐名称为必填项', trigger: 'blur' }],
  code: [{ required: true, message: '套餐编码为必填项', trigger: 'blur' }],
  helpCode: [{ required: true, message: '助记码为必填项', trigger: 'blur' }],
  sex: [{ required: true, message: '适用性别为必选项', trigger: 'change' }], // 从gender改为sex
  age: [{ required: true, message: '适用年龄为必填项', trigger: 'blur' }],
  price: [{ required: true, message: '价格为必填项', trigger: 'blur' }, { type: 'number', message: '价格必须为数字值' }],
});

// 表单引用
const dataAddForm = ref(null);
const dataEditForm = ref(null);

// 查找分页数据
const findPage = async () => {
  pagination.queryString = searchText.value; // 更新查询字符串
  try {
    const res = await axios.post('/setmeal/findPage', pagination);
    if (res.data) { // SetmealController.java的findPage直接返回PageResult
      dataList.value = res.data.rows;
      pagination.total = res.data.total;
    } else {
      ElMessage.error('获取分页数据失败');
    }
  } catch (error) {
    console.error('获取分页数据失败:', error);
    ElMessage.error('获取分页数据失败');
  }
};

// 处理页码改变
const handleCurrentChange = (currentPage) => {
  pagination.currentPage = currentPage;
  findPage();
};

// 处理每页显示条数改变
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  findPage();
};

// 重置表单数据和验证状态
const resetForm = () => {
  // 确保这里的 sex 字段与后端 Setmeal 实体一致
  Object.assign(formData, {
    id: null, name: null, code: null, helpCode: null, sex: '0', age: null, price: null, remark: null, attention: null, img: null
  });
  checkGroupIds.value = []; // 清空已选检查组
  imageUrl.value = ''; // 清空图片预览
  if (dataAddForm.value) {
    dataAddForm.value.resetFields();
  }
  if (dataEditForm.value) {
    dataEditForm.value.resetFields();
  }
};

// 查询所有检查组（用于新增/编辑弹窗中的穿梭框）
const findAllCheckGroups = async () => {
  try {
    const res = await axios.get('/checkgroup/findAll'); // 假设有findAll接口返回所有检查组
    if (res.data.flag) {
      checkGroupList.value = res.data.data;
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error('获取所有检查组失败:', error);
    ElMessage.error('获取所有检查组失败');
  }
};

// 处理图片上传成功
const handleImageSuccess = (response, uploadFile) => {
  if (response.flag) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    formData.img = response.data; // 后端返回的图片文件名
    ElMessage.success(response.message);
  } else {
    ElMessage.error(response.message);
    imageUrl.value = '';
    formData.img = null;
  }
};

// 图片上传前校验
const beforeImageUpload = (rawFile) => {
  const isJPGorPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPGorPNG) {
    ElMessage.error('图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
  }
  return isJPGorPNG && isLt2M;
};

// 显示新增弹窗
const handleAdd = () => {
  dialogFormVisible4Add.value = true;
  resetForm(); // 重置表单
  findAllCheckGroups(); // 加载所有检查组
};

// 新增确认
const handleAddConfirm = () => {
  dataAddForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const requestData = {
          setmeal: formData, // 套餐基本信息
          checkGroupIds: checkGroupIds.value, // 关联的检查组ID
        };
        const res = await axios.post('/setmeal/add', requestData);
        if (res.data.flag) {
          ElMessage.success(res.data.message);
          dialogFormVisible4Add.value = false;
          findPage(); // 重新查询
        } else {
          ElMessage.error(res.data.message);
        }
      } catch (error) {
        console.error('新增失败:', error);
        ElMessage.error('新增失败');
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入！');
      return false;
    }
  });
};

// 显示编辑弹窗并回显数据
const handleEdit = async (row) => {
  dialogFormVisible4Edit.value = true;
  resetForm(); // 先重置，再填充数据

  // 1. 查询套餐详情
  try {
    const resSetmeal = await axios.get('/setmeal/findById?id=' + row.id);
    if (resSetmeal.data.flag) {
      Object.assign(formData, resSetmeal.data.data); // 填充套餐基本信息
      // 如果有图片，设置图片预览
      if (formData.img) {
        imageUrl.value = 'http://q22u8a96w.bkt.clouddn.com/' + formData.img;
      }
    } else {
      ElMessage.error(resSetmeal.data.message);
      dialogFormVisible4Edit.value = false; // 查询失败则关闭弹窗
      return;
    }
  } catch (error) {
    console.error('查询套餐详情失败:', error);
    ElMessage.error('查询套餐详情失败');
    dialogFormVisible4Edit.value = false;
    return;
  }

  // 2. 查询所有检查组
  await findAllCheckGroups();

  // 3. 查询当前套餐关联的检查组ID
  try {
    const resGroupIds = await axios.get('/setmeal/findCheckGroupIdsBySetmealId?id=' + row.id);
    if (resGroupIds.data.flag) {
      checkGroupIds.value = resGroupIds.data.data; // 填充已选检查组
    } else {
      ElMessage.error(resGroupIds.data.message);
    }
  } catch (error) {
    console.error('查询关联检查组失败:', error);
    ElMessage.error('查询关联检查组失败');
  }
};

// 编辑确认
const handleEditConfirm = () => {
  dataEditForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const requestData = {
          setmeal: formData,
          checkGroupIds: checkGroupIds.value,
        };
        const res = await axios.post('/setmeal/edit', requestData); // 确保这里是 /setmeal/edit
        if (res.data.flag) {
          ElMessage.success(res.data.message);
          dialogFormVisible4Edit.value = false;
          findPage(); // 重新查询
        } else {
          ElMessage.error(res.data.message);
        }
      } catch (error) {
        console.error('编辑失败:', error);
        ElMessage.error('编辑失败');
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入！');
      return false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('您确定要删除当前数据吗？', '提示', {
    type: 'warning',
  })
      .then(async () => {
        try {
          const res = await axios.delete('/setmeal/delete?id=' + row.id); // 假设有delete接口
          if (res.data.flag) {
            ElMessage.success(res.data.message);
            findPage(); // 重新查询
          } else {
            ElMessage.error(res.data.message);
          }
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        ElMessage.info('操作已取消');
      });
};

// 组件挂载时执行分页查询
onMounted(() => {
  findPage();
});
</script>

<style scoped>
/* 新增的样式 */
.top-section-container {
  background-color: #f9f9f9;
  padding: 1.25rem 1.25rem 0.625rem;
  border-bottom: 3px solid #409EFF;
  margin-bottom: 1.25rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.bottom-section-container {
  background-color: #ffffff;
  padding: 1.25rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  border-radius: 0.25rem;
}

/* 现有样式调整 */
.content-header {
  padding-bottom: 0.625rem;
}

.filter-container {
  box-shadow: none;
  border-bottom: none;
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

.dialog-footer {
  text-align: right;
  margin-top: 1.25rem;
}

/* 调整 Element Plus 的图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 0.375rem; /* 6px -> 0.375rem */
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 1.75rem; /* 28px -> 1.75rem */
  color: #8c939d;
  width: 10.875rem; /* 174px -> 10.875rem */
  height: 10.875rem;
  text-align: center;
}
.avatar {
  width: 10.875rem;
  height: 10.875rem;
  display: block;
  object-fit: cover;
}

/* 调整穿梭框的高度和宽度 */
.el-transfer {
  width: 100%; /* 或根据需要调整 */
  display: flex; /* 使穿梭框内部组件 */
  justify-content: center; /* 居中对齐 */
  align-items: center; /* 垂直居中 */
}

/* 可以进一步调整穿梭框的具体列表高度 */
.el-transfer-panel {
  height: 20rem; /* 例如，设置一个固定高度 */
}

/* 调整 Element Plus 的 Checkbox 组进行布局调整 */
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}
.el-checkbox {
  margin-right: 1rem; /* 16px -> 1rem */
  margin-bottom: 0.625rem; /* 10px -> 0.625rem */
}

/* 整体表格字体大小调整 */
.datatable {
  font-size: 0.875rem; /* 14px / 16 = 0.875rem */
}
</style>